package org.mytools.dao.gener;

import java.util.List;

import org.mytools.util.StringUtils;

/**
 * 数据库表转换到Java域对象的包装类
 * 
 * @author Jacky.L
 * 
 */
public class DomainWrapper {

	private static final String DOMAIN_SUFFIX = ".java";
	private static final String TEMPLATE_NAME = "domain.vm";
	private static final String[][] MAPPING = { { "12", "VARCHAR", "String" },
			{ "-1", "LONGVARCHAR", "String" }, { "4", "INTEGER", "int" },
			{ "-5", "BIGINT", "long" }, { "1", "CHAR", "String" },
			{ "2", "NUMERIC", "double" }, { "3", "DECIMAL", "double" },
			{ "-7", "BIT", "int" }, { "-6", "TINYINT", "int" },
			{ "5", "SMALLINT", "int" }, { "7", "REAL", "float" },
			{ "6", "FLOAT", "double" }, { "8", "DOUBLE", "double" },
			{ "-2", "BINARY", "byte[]" }, { "-3", "VARBINARY", "byte[]" },
			{ "-4", "LONGVARBINARY", "byte[]" },
			{ "91", "DATE", "java.sql.Date" },
			{ "92", "TIME", "java.sql.Time" },
			{ "93", "TIMESTAMP", "java.sql.Timestamp" },
			{ "2005", "CLOB", "String" } };

	private static String spiltSeparator = "_";

	/**
	 * 设置拆分分隔符
	 * 
	 * @param separator
	 *            表名称分隔符
	 */
	public static void setSpiltSeparator(String separator) {
		spiltSeparator = separator;
	}

	/**
	 * 返回JDBC类型的JAVA类型名称
	 * 
	 * @param jdbcType
	 * @return JAVA类型名称
	 */
	public static String jdbcType2javaType(int jdbcType) {
		String javaType = null;

		for (int i = 0; i < MAPPING.length; i++) {
			if (MAPPING[i][0].equals(String.valueOf(jdbcType))) {
				javaType = MAPPING[i][2];
				break;
			}
		}
		if (javaType == null)
			throw new RuntimeException(jdbcType + " can't be matched!");

		return javaType;
	}

	/**
	 * 返回表名称的JAVA对象名
	 * 
	 * @param name
	 *            表名称
	 * @return JAVA对象名
	 * @see setSpiltSeparator(String separator)方法
	 */
	public static String objectName(String name) {
		List<String> strlist = StringUtils.splitToList(name, spiltSeparator);
		StringBuffer styleName = new StringBuffer();

		for (String str : strlist) {
			styleName.append(StringUtils.firstLetterUpper(str.toLowerCase()));
		}

		return styleName.toString();
	}

	/**
	 * 返回域对象的属性名
	 * 
	 * @param columnName
	 *            表的列名
	 * @return 域对象的属性名
	 */
	public static String getDomainPropertyName(String columnName) {
		return StringUtils.firstLetterLower(objectName(columnName));
	}

	/**
	 * 返回域对象的名称
	 * 
	 * @param tableName
	 *            表名称
	 * @return 域对象的名称
	 */
	public static String getDomainName(String tableName) {
		return objectName(tableName);
	}

	/**
	 * 返回域对象的后缀名称
	 * 
	 * @return 域对象的后缀名称
	 */
	public static String getDomainSuffix() {
		return DOMAIN_SUFFIX;
	}

	/**
	 * 返回域对象的生成模板的全路径名称，包括模板的名称
	 * 
	 * @param vmPath
	 *            模板路径
	 * @return 模板的全路径名称
	 */
	public static String getDomainTemplate(String vmPath) {
		return new StringBuffer().append(vmPath).append("/")
				.append(TEMPLATE_NAME).toString();
	}

}
